package com.pmcc.core.config.security;

import com.pmcc.core.entity.security.Employee;
import com.pmcc.core.entity.security.Role;
import com.pmcc.core.repository.EmployeeRepository;
import com.pmcc.core.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private EmployeeRepository employeeRepository;
    @Autowired
    private RoleRepository roleRepository;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询出人员的信息
        Employee employee = employeeRepository.findByUserName(username);


        if (employee == null) {
            throw new UsernameNotFoundException(String.format("查找不到该用户 '%s'.", username));
        } else if(employee.getEnabled()=="1"){
            throw new UsernameNotFoundException(String.format("该用户名已经被注销 '%s'.", username));
        }else if(employee.getDelFlag() ==1){
            throw new UsernameNotFoundException(String.format("该用户名已经被删除 '%s'.", username));
        }else{
            //查询出角色关联的信息
            Role role=roleRepository.findById(employee.getSysRoleId());
            return JwtUserFactory.create(employee,role);

        }
    }
}
